<template>
  <view class="container">
    <!-- 搜索框 -->
    <view class="search-box">
      <input class="search-input" type="text" placeholder="请输入商品名称" placeholder-class="placeholder-style">
    </view>
    
    <!-- 店铺信息 -->
    <view v-if="currentStore">
      <view class="store-card">
        <image class="store-logo" :src="`/static/${currentStore.imgUrl}`" mode="aspectFill"></image>
        <view class="store-info">
          <view class="store-name">{{currentStore.name}}</view>
          <view class="store-stats">
            <text>月售 {{currentStore.sales}}</text>
            <text>起送 ¥{{currentStore.expressLimit}}</text>
            <text>运费 ¥{{currentStore.expressPrice}}</text>
          </view>
          <view class="store-slogan">{{currentStore.slogan}}</view>
        </view>
      </view>
      <view class="divider"></view>
    </view>
    
    <!-- 商品分类和列表 -->
    <view class="content-wrapper">
      <view class="category-menu">
        <view @click="all()" :class="['menu-item', activeCategory === 'all' ? 'active' : '']">全部商品</view>
        <view @click="seckill()" :class="['menu-item', activeCategory === 'seckill' ? 'active' : '']">秒杀</view>
        <view @click="fruits()" :class="['menu-item', activeCategory === 'fruits' ? 'active' : '']">新鲜水果</view>
      </view>
      <scroll-view class="product-list" scroll-y>
        <view class="product-item" v-for="item in goods" :key="item._id">
          <image :src="`/static/${item.imgUrl}`" class="product-image" mode="aspectFill"></image>
          <view class="product-info">
            <view class="product-name">{{item.name}}</view>
            <view class="product-sales">月售 {{item.sales}} 件</view>
            <view class="price-container">
              <text class="current-price">¥{{item.price}}</text>
              <text class="original-price" v-if="item.oldPrice">¥{{item.oldPrice}}</text>
              <view class="product-actions">
                <text class="action-btn minus" @click.stop="decreaseQuantity(item)">-</text>
                <text class="product-quantity">{{getCartQuantity(item._id)}}</text>
                <text class="action-btn plus" @click.stop="increaseQuantity(item)">+</text>
              </view>
            </view>
          </view>
        </view>
      </scroll-view>
    </view>
    
    <!-- 底部购物车 -->
    <view class="cart-footer">
      <view class="cart-icon" @click="toggleCartPopup">
        <image src="/static/imgs/assets/basket.png" />
        <view class="badge" v-if="cartCount > 0">{{cartCount}}</view>
      </view>
      <view class="price-info">
        <text>总计:</text>
        <text class="total-price">¥{{currentStoreTotalPrice.toFixed(2)}}</text>
      </view>
      <view class="checkout-btn" @click="goToCart">去结算</view>
    </view>
    
    <!-- 购物车弹框（只显示当前店铺商品） -->
    <view class="cart-popup" v-if="showCartPopup" @click="toggleCartPopup">
      <view class="popup-content" @click.stop>
        <view class="popup-header">
          <text class="clear-cart" @click="clearCurrentStoreCart">清空购物车</text>
        </view>
        
        <scroll-view class="cart-list" scroll-y>
          <!-- 当前店铺的商品分组 -->
          <view class="store-group" v-if="currentStoreCartItems.length > 0">
            <view class="store-title">
              <checkbox :checked="isCurrentStoreAllSelected" @click="toggleCurrentStoreSelection">
                {{currentStore.name}}
              </checkbox>
            </view>
            
            <view class="cart-item" v-for="item in currentStoreCartItems" :key="item._id">
              <image :src="`/static/${item.imgUrl}`" class="cart-item-image"></image>
              <view class="cart-item-info">
                <view class="cart-item-name">{{item.name}}</view>
                <view class="cart-item-sales">月售 {{item.sales}} 件</view>
                <view class="price-container">
                  <view class="price-info">
                    <text class="current-price">¥{{item.price}}</text>
                    <text class="original-price" v-if="item.oldPrice">¥{{item.oldPrice}}</text>
                    <text class="subtotal">小计: ¥{{(item.price * item.quantity).toFixed(2)}}</text>
                  </view>
                  <view class="product-actions">
                    <text class="action-btn minus" @click.stop="decreaseQuantity(item)">-</text>
                    <text class="product-quantity">{{item.quantity}}</text>
                    <text class="action-btn plus" @click.stop="increaseQuantity(item)">+</text>
                  </view>
                </view>
              </view>
            </view>
          </view>
          
          <!-- 空购物车提示 -->
          <view v-else class="empty-cart">
            <image src="/static/imgs/assets/empty-cart.png" mode="aspectFit"></image>
            <text>购物车是空的</text>
          </view>
        </scroll-view>
        
        <!-- 购物车底部 -->
        <view class="cart-total">
          <view class="cart-icon">
            <image src="/static/imgs/assets/basket.png" />
            <view class="badge" v-if="currentStoreCartCount > 0">{{currentStoreCartCount}}</view>
          </view>
          <view class="total-price-container">
            <text>已选 {{currentStoreSelectedCount}} 件</text>
            <text>合计:</text>
            <text class="total-price">¥{{currentStoreTotalPrice.toFixed(2)}}</text>
          </view>
          <view class="checkout-btn" @click="goToCart">去结算</view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      currentStore: {},       
      goods: [],             
      superId: null,         
      activeCategory: 'all',  
      cartItems: [],          
      showCartPopup: false,  
    };
  },
  computed: {
    // 当前店铺的购物车商品
    currentStoreCartItems() {
      return this.cartItems.filter(item => item.storeId === this.superId);
    },
    // 当前店铺购物车商品数量
    currentStoreCartCount() {
      return this.currentStoreCartItems.reduce((total, item) => total + item.quantity, 0);
    },
    // 所有店铺购物车商品总数（底部购物车图标显示）
    cartCount() {
      return this.cartItems.reduce((total, item) => total + item.quantity, 0);
    },
    // 当前店铺已选商品数量
    currentStoreSelectedCount() {
      return this.currentStoreCartItems.reduce((count, item) => {
        return count + (item.isSelected ? item.quantity : 0);
      }, 0);
    },
    // 当前店铺是否全选
    isCurrentStoreAllSelected() {
      return this.currentStoreCartItems.length > 0 && 
             this.currentStoreCartItems.every(item => item.isSelected);
    },
    // 当前店铺购物车总金额
    currentStoreTotalPrice() {
      return this.currentStoreCartItems.reduce((total, item) => {
        return total + (item.isSelected ? item.price * item.quantity : 0);
      }, 0);
    }
  },
  onLoad(options) {
    this.superId = options.id;
    this.loadStoreData();
    this.loadCartData();
    this.all(); // 默认加载全部商品
  },
  methods: {
    // 加载店铺数据
    loadStoreData() {
      uni.request({
        url: `https://67f85eae7719dfcd4b47e8f1.hz-iframe-svc.simplelab.cn/hotList?_id=${this.superId}`,
        success: (res) => {
          this.currentStore = res.data[0];
        }
      });
    },
    // 加载购物车数据
    loadCartData() {
      const savedCartItems = uni.getStorageSync('cartItems') || [];
      this.cartItems = savedCartItems;
    },
    // 商品分类方法
    all() {
      this.activeCategory = 'all';
      this.fetchProducts(`https://67f85eae7719dfcd4b47e8f1.hz-iframe-svc.simplelab.cn/products-all?shopId=${this.superId}`);
    },
    seckill() {
      this.activeCategory = 'seckill';
      this.fetchProducts(`https://67f85eae7719dfcd4b47e8f1.hz-iframe-svc.simplelab.cn/products-seckill?shopId=${this.superId}`);
    },
    fruits() {
      this.activeCategory = 'fruits';
      this.fetchProducts(`https://67f85eae7719dfcd4b47e8f1.hz-iframe-svc.simplelab.cn/products-fruit?shopId=${this.superId}`);
    },
    // 通用商品加载方法
    fetchProducts(url) {
      uni.request({
        url: url,
        success: (res) => {
          this.goods = res.data;
        }
      });
    },
    // 购物车操作
    toggleCartPopup() {
      this.showCartPopup = !this.showCartPopup;
    },
    increaseQuantity(item) {
      const existingItem = this.cartItems.find(i => i._id === item._id);
      if (existingItem) {
        existingItem.quantity += 1;
      } else {
        this.addNewItemToCart(item);
      }
      this.saveCartData();
    },
    decreaseQuantity(item) {
      const existingItem = this.cartItems.find(i => i._id === item._id);
      if (existingItem) {
        if (existingItem.quantity > 1) {
          existingItem.quantity -= 1;
        } else {
          this.cartItems = this.cartItems.filter(i => i._id !== item._id);
        }
        this.saveCartData();
      }
    },
    addNewItemToCart(item) {
      this.cartItems.push({
        ...item,
        quantity: 1,
        isSelected: true,
        storeId: this.superId,
        storeName: this.currentStore.name
      });
    },
    // 获取商品在购物车中的数量
    getCartQuantity(productId) {
      const item = this.cartItems.find(i => i._id === productId);
      return item ? item.quantity : 0;
    },
    // 清空当前店铺购物车
    clearCurrentStoreCart() {
      this.cartItems = this.cartItems.filter(item => item.storeId !== this.superId);
      this.saveCartData();
      this.showCartPopup = false;
    },
    // 切换当前店铺全选状态
    toggleCurrentStoreSelection() {
      const newState = !this.isCurrentStoreAllSelected;
      this.currentStoreCartItems.forEach(item => {
        item.isSelected = newState;
      });
      this.saveCartData();
    },
    // 保存购物车数据
    saveCartData() {
      uni.setStorageSync('cartItems', this.cartItems);
    },
    // 去结算
    goToCart() {
      // 只传递当前店铺的商品
      const selectedItems = this.currentStoreCartItems.map(item => ({
        ...item,
        storeName: this.currentStore.name,
        storeId: this.superId
      }));
      uni.setStorageSync('selectedCartItems', selectedItems);
      uni.navigateTo({
        url: '/pages/must/must'
      });
    }
  }
};
</script>

<style scoped>
.price-container {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-top: 20rpx;
}

.product-actions {
  display: flex;
  align-items: center;
  gap: 15rpx;
}

.action-btn {
  width: 50rpx;
  height: 50rpx;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 32rpx;
}

.plus {
  background-color: #1b76f6;
  color: #fff;
}

.minus {
  background-color: #f5f5f5;
  color: #666;
}

.product-quantity {
  min-width: 40rpx;
  text-align: center;
  font-size: 28rpx;
}
/* 原样式 */
.container {
  padding-bottom: 100rpx;
  background-color: #f8f8f8;
  min-height: 100vh;
}

/* 搜索框样式 */
.search-box {
  padding: 20rpx 30rpx;
  background-color: #fff;
}

.search-input {
  height: 70rpx;
  background-color: #f5f5f5;
  border-radius: 35rpx;
  padding: 0 30rpx;
  font-size: 28rpx;
}

.placeholder-style {
  color: #999;
}

/* 店铺卡片样式 */
.store-card {
  display: flex;
  padding: 30rpx;
  background-color: #fff;
}

.store-logo {
  width: 140rpx;
  height: 140rpx;
  border-radius: 8rpx;
}

.store-info {
  flex: 1;
  margin-left: 30rpx;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.store-name {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.store-stats {
  font-size: 24rpx;
  color: #666;
}

.store-stats text {
  margin-right: 20rpx;
}

.store-slogan {
  font-size: 24rpx;
  color: #e74c3c;
}

.divider {
  height: 20rpx;
  background-color: #f5f5f5;
}

/* 内容区域 */
.content-wrapper {
  display: flex;
  height: calc(100vh - 400rpx);
}

.category-menu {
  width: 180rpx;
  background-color: #fff;
}

.menu-item {
  padding: 30rpx 20rpx;
  font-size: 28rpx;
  color: #666;
  text-align: center;
  border-left: 6rpx solid transparent;
}

.menu-item.active {
  color: #e74c3c;
  font-weight: bold;
  border-left-color: #e74c3c;
  background-color: #fef0f0;
}

.product-list {
  flex: 1;
  padding: 20rpx;
  background-color: #fff;
}

.product-item {
  display: flex;
  padding: 20rpx 0;
  border-bottom: 1rpx solid #f0f0f0;
}

.product-image {
  width: 160rpx;
  height: 160rpx;
  border-radius: 8rpx;
}

.product-info {
  flex: 1;
  margin-left: 20rpx;
  position: relative;
}

.product-name {
  font-size: 28rpx;
  color: #333;
  line-height: 1.4;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
  overflow: hidden;
}

.product-sales {
  font-size: 24rpx;
  color: #999;
  margin-top: 10rpx;
}

.price-container {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-top: 20rpx;
}

.current-price {
  font-size: 32rpx;
  color: #e74c3c;
  font-weight: bold;
}

.original-price {
  font-size: 24rpx;
  color: #999;
  text-decoration: line-through;
}


/* 底部购物车 */
.cart-footer {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  height: 100rpx;
  background-color: #fff;
  display: flex;
  align-items: center;
  padding: 0 30rpx;
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.1);
  z-index: 10;
}

.cart-icon {
  position: relative;
  width: 60px; /* 调整宽度 */
  height: 60px; /* 调整高度 */
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 20rpx;
}
.cart-icon image{
   width:70px;
  height:35px;
  margin-left: 25px;
}


.cart-icon .iconfont {
  color: #fff;
  font-size: 40rpx;
}

.badge {
  position: absolute;
  top: -10rpx;
  right: -10rpx;
  min-width: 36rpx;
  height: 36rpx;
  background-color: #e74c3c;
  color: #fff;
  border-radius: 18rpx;
  font-size: 20rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 0 8rpx;
}

.price-info {
  flex: 1;
  font-size: 28rpx;
  color: #666;
}

.total-price {
  color: #e74c3c;
  font-weight: bold;
  margin-left: 15px;
}

.checkout-btn {
  width: 200rpx;
  height: 70rpx;
  background-color: #1b76f6;
  color: #fff;
  font-size: 28rpx;
  border-radius: 35rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

/* 购物车弹框样式 */
.cart-popup {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 100;
  display: flex;
  flex-direction: column;
  justify-content: flex-end;
}

.popup-content {
  background-color: #fff;
  border-radius: 20rpx 20rpx 0 0;
  max-height: 70vh;
  padding: 30rpx;
}

.popup-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-bottom: 20rpx;
  border-bottom: 1rpx solid #eee;
}

.select-all {
  display: flex;
  align-items: center;
}

.select-all checkbox {
  margin-right: 10rpx;
}

.clear-cart {
  font-size: 26rpx;
  color: #666;
}

.cart-list {
  max-height: 50vh;
  margin-top: 20rpx;
}

.cart-item {
  display: flex;
  align-items: center;
  padding: 20rpx 0;
  border-bottom: 1rpx solid #f5f5f5;
}

.select-item {
  margin-right: 10rpx;
}

.cart-item-image {
  width: 100rpx;
  height: 100rpx;
  border-radius: 8rpx;
  margin-right: 20rpx;
}

.cart-item-info {
  flex: 1;
}

.cart-item-name {
  font-size: 28rpx;
  margin-bottom: 5rpx;
}

.cart-item-sales {
  font-size: 24rpx;
  color: #999;
}

.price-container {
  display: flex;
  align-items: center;
}

.current-price {
  font-size: 32rpx;
  color: #e74c3c;
  font-weight: bold;
}

.original-price {
  font-size: 24rpx;
  color: #999;
  text-decoration: line-through;
  margin-left: 10rpx;
}


.cart-total {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-top: 20rpx;
}

.cart-icon {
  position: relative;
  width: 60px;
  height: 60px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 20rpx;
}

.cart-icon image {
  width: 70px;
  height: 35px;
  margin-left: 25px;
}

.badge {
  position: absolute;
  top: -10rpx;
  right: -10rpx;
  min-width: 36rpx;
  height: 36rpx;
  background-color: #e74c3c;
  color: #fff;
  border-radius: 18rpx;
  font-size: 20rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 0 8rpx;
}

.total-price-container {
  display: flex;
  align-items: center;
}

.total-price {
  color: #e74c3c;
  font-weight: bold;
  margin-left: 10rpx;
}

.checkout-btn {
  width: 200rpx;
  height: 70rpx;
  background-color: #1b76f6;
  color: #fff;
  font-size: 28rpx;
  border-radius: 35rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

/* 添加新样式 */
.store-group {
  margin-bottom: 20rpx;
  background: #fff;
  border-radius: 12rpx;
}

.store-title {
  padding: 20rpx;
  font-size: 28rpx;
  font-weight: bold;
  border-bottom: 1rpx solid #f5f5f5;
}

.subtotal {
  font-size: 24rpx;
  color: #666;
  margin-left: 20rpx;
}

.price-info {
  display: flex;
  align-items: center;
  flex: 1;
}

.total-price-container text {
  margin-right: 10rpx;
}
/* 原有样式保持不变，只需确保新增的empty-cart样式 */
.empty-cart {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 100rpx 0;
}
.empty-cart image {
  width: 200rpx;
  height: 200rpx;
  margin-bottom: 30rpx;
}
.empty-cart text {
  color: #999;
  font-size: 28rpx;
}
</style>
